<template>
  <!-- 通道费月账单 -->
  <div class="home-page-container">
    <!-- search 查询 -->
    <el-card shadow="never">
      <div v-if="company" class="company-info">
        <span class="info-label">商户名称: </span>
        <span class="info-item">{{userInfo.companyName || ''}}</span>
      </div>
      <mer-search :searchConfig="formConfig" :searchBar="searchBar"
        @search="search"
        @reset="reset(initQuery)"
        @changeTime="(value,model)=>changeTime(value,'searchBar', 'settlementDateStart', 'settlementDateEnd')"
        :loading="tableLoading">
        <template slot="handler">
          <el-button size="mini" @click="download" icon="el-icon-download">导出</el-button>
        </template>
      </mer-search>
    </el-card>
    <!-- summary 汇总信息 本期取消-->
    <!-- <el-card style="margin: 20px 0 10px" shadow="never">
      <div class="sum-wrapper">
        <div class="sum-item sum-item-1">
          <div class="value">{{sumInfo.totalOilAmount}}</div>
          <div class="label">加油总金额(元)</div>
        </div>
        <div class="sum-item sum-item-2">
          <div class="value">{{sumInfo.totalRebateAmount}}</div>
          <div class="label">让利总金额(元)</div>
        </div>
        <div class="sum-item sum-item-3">
          <div class="value">{{sumInfo.totalPayAmount}}</div>
          <div class="label">实付总金额(元)</div>
        </div>
        <div class="sum-item sum-item-4">
          <div class="value">{{sumInfo.totalSlottingAmount}}</div>
          <div class="label">通道费总金额(元)</div>
        </div>
        <div class="sum-item sum-item-5">
          <div class="value">{{sumInfo.totalSettlementAmount}}</div>
          <div class="label">结算总金额(元)</div>
        </div>
      </div>
    </el-card> -->
    <!-- table 表格 -->
    <el-card shadow="never" style="margin: 20px 0">
      <el-table
        :data="tableData.records"
        :border="true"
        stripe
        size="small"
        v-loading="tableLoading"
        style="width: 100%">
        <el-table-column
          prop="billMonth"
          label="账单月份"
          align="center">
        </el-table-column>
        <!-- 油站权限展示 -->
        <template v-if="!company">
          <el-table-column
            prop="gasName"
            label="油站名称"
            align="center">
          </el-table-column>
          <el-table-column
            prop="slottingFee"
            align="center">
            <!-- slot为header中的回调参数并无row，这里取row是为了触发重新渲染 -->
            <template slot="header" slot-scope="{row}">
              <div>
                {{ businessSource === 0 && !row ? '应付通道费金额（团油收单）' : '应付通道费金额（POS收单）' }}
              </div>
            </template>
            <template slot-scope="{row}">
              <div>
                {{ row.slottingFee }}
              </div>
            </template>
          </el-table-column>
        </template>
        <!-- 商户权限展示 -->
        <template v-else>
          <el-table-column
            prop="billAmount"
            align="center">
            <!-- slot为header中的回调参数并无row，这里取row是为了触发重新渲染 -->
            <template slot="header">
              <div>
                {{ businessSource === 0 ? '应付通道费金额（团油收单）' : '应付通道费金额（POS收单）' }}
              </div>
            </template>
            <template slot-scope="{row}">
              <div>
                {{ row.billAmount }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="billAmountSettlement"
            align="center">
            <!-- slot为header中的回调参数并无row，这里取row是为了触发重新渲染 -->
            <template slot="header" slot-scope="{row}">
              <div>
                {{ businessSource === 0 && !row ? '实付通道费金额（团油收单）' : '实付通道费金额（POS收单）' }}
              </div>
            </template>
            <template slot-scope="{row}">
              <div>
                {{ row.billAmountSettlement }}
              </div>
            </template>
          </el-table-column>
        </template>

        <el-table-column
          prop="billStatusName"
          label="账单状态"
          align="center">
        </el-table-column>
        <el-table-column
          prop="billCreateTime"
          label="账单生成时间"
          align="center">
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="pageChange"
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
import listPage from '@/mixins/listPage'
import queryMix from '@/views/finance/mixins/query';
import { getMonthlyQueryStatusApi, getMonthlyBillListApi, downloadMonthlyBillApi, getIfHasPos, queryShowStationOrCompany } from '@/api/finance'
import moment from 'moment'
import {mapGetters} from 'vuex'

const businessSourceList = [
  { value: 0, name: '团油收单' },
  { value: 1, name: 'pos收单' }
]

// 查询表单配置
let formConfig_gas = [
  { label: '油站', type: 'select', modelName: 'gasId', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'gasName', selectValue: 'gasId' },
  { label: '账单月份', type: 'date', modelName: 'tradeTime', model: '', dateType: 'monthrange', format: 'yyyy-MM',pickerOptions:{}, clearable:false },
  { label: '账单状态', type: 'select', modelName: 'billStatus', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'label', selectValue: 'value' },
]
let formConfig_company = [
  { label: '账单月份', type: 'date', modelName: 'tradeTime', model: '', dateType: 'monthrange', format: 'yyyy-MM',pickerOptions:{}, clearable:false },
  { label: '账单状态', type: 'select', modelName: 'billStatus', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'label', selectValue: 'value' },
]

// 查询是否开通过POS
async function checkHasPos () {
  try {
    const { result } = await getIfHasPos()
    if (result) {
      const pos_item = { label: '收单方式', type: 'select', modelName: 'businessSource', placeholder: '', selectOptions: businessSourceList, define: true, selectLabel: 'name', selectValue: 'value', clearable: false }
      if (!formConfig_gas.find(item => item.modelName === 'businessSource')) formConfig_gas.push(pos_item)
      if (!formConfig_company.find(item => item.modelName === 'businessSource')) formConfig_company.push(pos_item)
    }
  } catch (error) {
    console.log(error)
  }
}

export default {
  name: 'bill_monthlyBill',
  mixins:[ listPage, queryMix ],
  data(){
    return{
      company: false,
      tradeTime:'',
      formConfig: formConfig_company,
      total: 0,
      businessSource: 0,
      searchBar: {
        businessSource: 0
      },
      sumInfo:{
        totalOilAmount: '0.00',
        totalRebateAmount: '0.00',
        totalPayAmount: '0.00',
        totalSlottingAmount: '0.00',
        totalSettlementAmount: '0.00'
      },
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime();
          if (maxDate) {
            this.selectDate = ''
          }
        },
        // 限制时间选择范围366天
        disabledDate: (time) => {
          if (this.selectDate !== '') {
            const one = 365 * 24 * 3600 * 1000;
            const minTime = this.selectDate - one;
            const maxTime = this.selectDate + one;
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      }
    }
  },
  async created(){
    checkHasPos()
    // 查询展示油站or商户
    const { code, result } = await queryShowStationOrCompany()
    if (code !== 200) return
    this.company = result === 1
    this.initPage()
  },
  computed:{
    ...mapGetters(['userInfo'])
  },
  methods:{
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.initPage()
    },
    pageChange (val) {
      this.pagination.pageIndex = val
      this.initPage()
    },
    /**
     * 查询列表
     */
    search () {
      this.pagination.pageIndex = 1
      this.businessSource = this.searchBar.businessSource
      // this.pagination.pageSize = 10
      this.refresh()
    },
    initPage () {
      this.initSearchAndTable()
      this.getAllQueryProps()
      this.initQuery()
      this.initList(getMonthlyBillListApi,false)
    },  
    // 设置默认查询条件，默认时间间隔一年
    initQuery () {
      this.tradeTime = ''
      this.initMonth()
      const { tradeTime, pickerOptions } = this
      const initObj = { tradeTime: [tradeTime, pickerOptions] }
      this.setSearchConfig(initObj)
    },
    initMonth(){
      const start = moment().year(moment().year() - 1).startOf('month').format('YYYY-MM-DD HH:mm:ss')
      const end = moment().year(moment().year()).startOf('month').format('YYYY-MM-DD HH:mm:ss')
      this.tradeTime = [start,end]
      this.searchBar['settlementDateStart'] = moment(start).format('YYYY-MM')
      this.searchBar['settlementDateEnd'] = moment(end).format('YYYY-MM')
    },
    getAllQueryProps(){
      // 获取查询条件：油站
      if(!this.company){
        this.getAllGasStations()
      }
      this.getQueryStatus()
    },
    //动态生成表格及其查询条件
    initSearchAndTable(){
      // 获取用户信息
      //商户显示商户名称，去掉油站查询
      //商户不显示   油站名称
      //油站不显示   实付
      if(this.company){
        this.formConfig = formConfig_company
      }else{
        this.formConfig = formConfig_gas
      }
    },
     // 获取查询条件：账单状态
    async getQueryStatus(){
      try{
        const { code, result = [] } = await getMonthlyQueryStatusApi()
        if(code !== 200) return
        const initObj = { billStatus: this.optionsWrapper(result) }
        this.setSearchConfig(initObj)
      }catch(err){
        console.log(err)
      }
    },
    //导出
    download () {
      this.downloadFile(downloadMonthlyBillApi,'通道费月账单')
    },
    reset () {
      this.searchBar = { businessSource: 0 }
      this.initQuery()
      this.search()
    }
  }
}
</script>
<style lang="less" scoped>
.home-page-container{
  margin-top: 20px;
}
.sum-wrapper{
  display: flex;
  flex-flow: nowrap;
  color: #222;
  .sum-item{
    margin-right: 106px;
    padding-left: 10px;
    .value{
      font-size:26px;
      font-weight:bold;
      margin-bottom: 5px;
    }
    .label{
      font-size:14px;
    }
  }
  .sum-item-1{
    border-left: 3px solid #C93A02;
  }
  .sum-item-2{
    border-left: 3px solid #E7B911;
  }
  .sum-item-3{
    border-left: 3px solid #027CC9;
  }
  .sum-item-4{
    border-left: 3px solid #9A02C9;
  }
  .sum-item-5{
    border-left: 3px solid #A6C902;
  }
}
.company-info{
  margin-bottom: 15px;
  .info-label{
    font-size: 16px;
    color: #606266;
    font-weight: 600;
  }
  .info-item{
    font-size: 16px;
    color: #606266;
  }
}
.pagination {
  margin-top: 20px;
  padding-bottom: 20px;
  float: right;
}
</style>